package com.qianniu.napi.common.util;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by chenxuebin on 16/9/12.
 */
public class HttpUtils {

    private final static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 向指定ulr发起post请求，并返回请求结果
     *
     * @param url
     * @param formParams
     * @return
     */
    public static String httpPost(String url, List<NameValuePair> formParams) {
        String json = "";
        HttpPost httpPost = new HttpPost(url); // 目标地址URL
        HttpClient httpclient = HttpClients.createDefault();
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, "utf-8"));
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                logger.error("getMsgFromHttpPost failed,url:" + url + ",http StatusCode:" + response.getStatusLine().getStatusCode() + ",post parameter:[" + JSON.toJSONString(formParams) + "]");
            } else {
                json = EntityUtils.toString(entity);
                EntityUtils.consume(entity);
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("get msg from http post fail:",e);
        } catch (IOException e) {
            logger.error("get msg from http post err:", e);
        } finally {
            httpPost.releaseConnection();
            httpclient = null;
            httpPost = null;
        }
        return json;
    }

    /**
     * 向指定ulr发起post请求，并返回请求结果
     *
     * @param url
     * @param content
     * @return
     */
    public static String httpPost(String url, String content) {
        String json = "";
        HttpPost httpPost = new HttpPost(url); // 目标地址URL
        HttpClient httpclient = HttpClients.createDefault();
        try {
            httpPost.setHeader("Content-Type","text/plain; charset=UTF-8");
            httpPost.setEntity(new StringEntity(content,"UTF-8"));
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                logger.error("getMsgFromHttpPost failed,url:" + url + ",http StatusCode:" + response.getStatusLine().getStatusCode());
            } else {
                json = EntityUtils.toString(entity);
                EntityUtils.consume(entity);
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("get msg from http post fail:",e);
        } catch (IOException e) {
            logger.error("get msg from http post err:", e);
        } finally {
            httpPost.releaseConnection();
            httpclient = null;
            httpPost = null;
        }
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>> postFile result json = "+json);
        return json;
    }

    public static String postFile(String url,String key,String filePath)  {

        logger.debug(">>>>>> start to postFile at url = "+url);
        String json = "";
        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        try {
            FileBody fileBody = new FileBody(new File(filePath));

            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            entityBuilder.addPart(key, fileBody);
//            entityBuilder.setCharset(Charset.defaultCharset());
//            entity.addBinaryBody("media", new File(filePath));

            httpPost.setEntity(entityBuilder.build());
            HttpResponse response = httpclient.execute(httpPost);

            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                logger.error("postFile failed,url:" + url + ",http StatusCode:" + response.getStatusLine().getStatusCode());
            } else {
                json = EntityUtils.toString(entity);
                EntityUtils.consume(entity);
            }
        }
        catch (UnsupportedEncodingException e) {
            logger.error("get msg from http post fail:",e);
        } catch (IOException e) {
            logger.error("get msg from http post err:", e);
        } finally {
            httpPost.releaseConnection();
            httpclient = null;
            httpPost = null;
        }
        return json;
    }


    public static String postFile(String url,String key,String filePath,
                                  String paramKey,String paramValue)  {

        logger.debug(">>>>>> start to postFile at url = "+url);
        String json = "";
        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        try {
            FileBody fileBody = new FileBody(new File(filePath));

            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            entityBuilder.addPart(key, fileBody);
            if(!Strings.isNullOrEmpty(paramKey)){
                logger.debug(">>>addPart");
//                entityBuilder.addTextBody(paramKey, paramValue);
                StringBody stringBody = new StringBody(paramValue,ContentType.APPLICATION_JSON);
                entityBuilder.addPart(paramKey, stringBody);
            }
//            entityBuilder.setCharset(Charset.defaultCharset());
//            entity.addBinaryBody("media", new File(filePath));

            httpPost.setEntity(entityBuilder.build());
            HttpResponse response = httpclient.execute(httpPost);

            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                logger.error("postFile failed,url:" + url + ",http StatusCode:" + response.getStatusLine().getStatusCode());
            } else {
                json = EntityUtils.toString(entity);
                EntityUtils.consume(entity);
            }
        }
        catch (UnsupportedEncodingException e) {
            logger.error("get msg from http post fail:",e);
        } catch (IOException e) {
            logger.error("get msg from http post err:", e);
        } finally {
            httpPost.releaseConnection();
            httpclient = null;
            httpPost = null;
        }
        return json;
    }

    /**
     * 获取指定url资源
     * @param url
     * @return
     */
    public static String httpGet(String url) {
        HttpClient httpclient = HttpClients.createDefault();

        HttpGet httpget = new HttpGet(url);
        StringBuilder sb = new StringBuilder();
        // logger.debug("=============================start print get url==========================");
        // logger.debug(url);
        try {
            HttpResponse response = httpclient.execute(httpget);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                String content = "httpGet failed,url:" + url + ",http StatusCode:" + response.getStatusLine().getStatusCode();
                logger.error(content);
            } else {
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
                String lineStr;
                while ((lineStr = reader.readLine()) != null) {
                    sb.append(lineStr);
                }
                reader.close();
            }
        } catch (Exception e) {
            logger.error("======error",e);
        } finally {
            httpget.releaseConnection();
        }
        String result = sb.toString();
//        logger.debug("result from http get:" + result);
        return result;
    }

    /**
     * 获取指定url资源
     * @param url
     * @return
     */
    public static String httpPostWithCookie(String url, List<NameValuePair> formParams) {

        CookieStore cookieStore=new BasicCookieStore();

        BasicClientCookie JSESSIONID = new BasicClientCookie("JSESSIONID", "AC8833EE69DF323AB4D63FC8D3597D2A");
        JSESSIONID.setVersion(0);
        JSESSIONID.setDomain("nfyx.jlbry.com");
        JSESSIONID.setPath("/precision/pc/secret/member/index");
        cookieStore.addCookie(JSESSIONID);

        BasicClientCookie route = new BasicClientCookie("route", "11bbb550c111f73fd67c4ec53977cf36");
        route.setVersion(0);
        route.setDomain("nfyx.jlbry.com");
        route.setPath("/precision/pc/secret/member/index");
        cookieStore.addCookie(route);

        BasicClientCookie JUNLEBAO = new BasicClientCookie("JUNLEBAO", "ZDVBcHg4UC9OUFdiYTE1cUUxWnRabFl2VlVMalZaRXNDRUxucFZxanlWVitpeGNyQkhBcDVxdVI0MFBkSGJoRDQwbDRjdGFUUWpuQ1BsWUxrT2pJTFh5d056S1NOdEwycmxpRHQ0ekh6MjFBWjRMMk91OGlrMzJaRlJPQ1I4LzFhdlgwcFo1UG9KanZPVmVMa3pOZnR1T2xrbEN6R2RvNzBjVmtzMkNmMG5zaHM5N3JYU3VIbExTbkQ1TmpJN1VvdWdnbnFsL252ZTlJMlVRTU5UU01GSzk2YnFlK1hSUkx3bXdQOUhCdDFUZWJ4UFNTYnlXM29xTUFWQmZ2c0hJNnJOYkZoMm9rNUM5dTdNTHEzVWRta2tmT1l3SGRtOUs0RjNtcjhHRWdLWG41N0h5TWNoczNaRjRJaWxTMS9sZ2ZTMnpNMGFkdlhzeFMzeWdkRFBMTndGSlRLN2pGZi9GdHRaejNTUS9PQzI2ZGdDSGVmZmgwWmRyTVhxN1dVa0R3NHV1MDRPc0FHaHhUTzl4OGdtbzlBcEgzMDNEOHR3dGNYZzdQTzIwUG9qNi85L2RzNHgvY3dTTVVNdnEwSWFzbHJIZlk2MHdoZWRPSGtDRENBRUExandzZlRsMkhkeldtcHVCRGZWMksyb2JlUUdZS0owMWd1Vi9lYmk4Tk9lK2gwaFk4MGQ1NHhNS283TUR4MVRNMFFERVpubjdVd004UW1MSE5lTW4rQTU3VUhXckM1aXpxNW85N2UzUW40YUNrNjRqZ2NyRjVRWHh4Qk93cnBlYW9FU0ppL1R6TzZpRjZCNXRXSFRlN2J4dHBYUWJudzh4K0UwL281ZEdzaUVsMDhYNk15K0xRYjdhTnR6bTFtUnVQUlFBbUdVdENaYTRtVHovQ2tYMlVVaEtTWlJ4K05lcGhOS09jMEdTWExSWW1oMDBsQVVaT0drMDRzcEg5cWhaanJGMDJyemY4USt3UFVUdGdsa25ZakkveExxKzM5NDIxbUdwV3NQV3VxQTlmaFdSeGtMLzlCUU9ieUpETVNiNVpWeVl4YkkzWjdCbndsN0dHYzBMYm1oWDZYWDVQQUN1VGtON3ljalJSTVlIRVZYcGEvMHVXOHA0PQ==");
        JUNLEBAO.setVersion(0);
        JUNLEBAO.setDomain("nfyx.jlbry.com");
        JUNLEBAO.setPath("/precision/pc/secret/member/index");
        cookieStore.addCookie(JUNLEBAO);

        HttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

        HttpPost httpPost = new HttpPost(url);
        StringBuilder sb = new StringBuilder();
        String result = "";
        // logger.debug("=============================start print get url==========================");
        // logger.debug(url);
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, "gbk"));
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                logger.error("getMsgFromHttpPost failed,url:" + url + ",http StatusCode:" + response.getStatusLine().getStatusCode() + ",post parameter:[" + JSON.toJSONString(formParams) + "]");
            } else {
                result = EntityUtils.toString(entity);
                EntityUtils.consume(entity);
            }
        } catch (Exception e) {
            logger.error("======error",e);
        } finally {
            httpPost.releaseConnection();
        }
        logger.info("result from http get:" + result);
        return result;
    }

    /**
     * 获取指定url资源
     * @param url
     * @return
     */
    public static String httpGetWithCookie(String url, List<NameValuePair> formParams) {

        CookieStore cookieStore=new BasicCookieStore();

        BasicClientCookie JSESSIONID = new BasicClientCookie("JSESSIONID", "61E979EE14D3D17C1E6A8EED1D0232BA");
        JSESSIONID.setVersion(0);
        JSESSIONID.setDomain("nfyx.jlbry.com");
        JSESSIONID.setPath("/precision/pc/secret/member/index");
        cookieStore.addCookie(JSESSIONID);

        BasicClientCookie route = new BasicClientCookie("route", "11bbb550c111f73fd67c4ec53977cf36");
        route.setVersion(0);
        route.setDomain("nfyx.jlbry.com");
        route.setPath("/precision/pc/secret/member/index");
        cookieStore.addCookie(route);

        BasicClientCookie JUNLEBAO = new BasicClientCookie("JUNLEBAO", "ZDVBcHg4UC9OUFdiYTE1cUUxWnRabFl2VlVMalZaRXNDRUxucFZxanlWVitpeGNyQkhBcDVxdVI0MFBkSGJoRDQwbDRjdGFUUWpuQ1BsWUxrT2pJTFh5d056S1NOdEwycmxpRHQ0ekh6MjFBWjRMMk91OGlrMzJaRlJPQ1I4LzFhdlgwcFo1UG9KanZPVmVMa3pOZnR1T2xrbEN6R2RvNzBjVmtzMkNmMG5zaHM5N3JYU3VIbExTbkQ1TmpJN1VvdWdnbnFsL252ZTlJMlVRTU5UU01GSzk2YnFlK1hSUkx3bXdQOUhCdDFUZWJ4UFNTYnlXM29xTUFWQmZ2c0hJNnJOYkZoMm9rNUM5dTdNTHEzVWRta2tmT1l3SGRtOUs0RjNtcjhHRWdLWG41N0h5TWNoczNaRjRJaWxTMS9sZ2ZTMnpNMGFkdlhzeFMzeWdkRFBMTndGSlRLN2pGZi9GdHRaejNTUS9PQzI2ZGdDSGVmZmgwWmRyTVhxN1dVa0R3NHV1MDRPc0FHaHhUTzl4OGdtbzlBcEgzMDNEOHR3dGNYZzdQTzIwUG9qNi85L2RzNHgvY3dTTVVNdnEwSWFzbHJIZlk2MHdoZWRPSGtDRENBRUExandzZlRsMkhkeldtcHVCRGZWMksyb2JlUUdZS0owMWd1Vi9lYmk4Tk9lK2gwaFk4MGQ1NHhNS283TUR4MVRNMFFERVpubjdVd004UW1MSE5lTW4rQTU3VUhXckM1aXpxNW85N2UzUW40YUNrNjRqZ2NyRjVRWHh4Qk93cnBlYW9FU0ppL1R6TzZpRjZCNXRXSFRlN2J4dHBYUWJudzh4K0UwL281ZEdzaUVsMDhYNk15K0xRYjdhTnR6bTFtUnVQUlFBbUdVdENaYTRtVHovQ2tYMlVVaEtTWlJ4K05lcGhOS09jMEdTWExSWW1oMDBsQVVaT0drMDRzcEg5cWhaanJGMDJyemY4USt3UFVUdGdsa25ZakkveExxKzM5NDIxbUdwV3NQV3VxQTlmaFdSeGtMLzlCUU9ieUpETVNiNVpWeVl4YkkzWjdCbndsN0dHYzBMYm1oWDZYWDVQQUN1VGtON3ljalJSTVlIRVZYcGEvMHVXOHA0PQ====");
        JUNLEBAO.setVersion(0);
        JUNLEBAO.setDomain("nfyx.jlbry.com");
        JUNLEBAO.setPath("/precision/pc/secret/member/index");
        cookieStore.addCookie(JUNLEBAO);

        HttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

        HttpGet httpget = new HttpGet(url);
        StringBuilder sb = new StringBuilder();
        String result = "";
        // logger.debug("=============================start print get url==========================");
        // logger.debug(url);
        try {
            HttpResponse response = httpclient.execute(httpget);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                String content = "httpGet failed,url:" + url + ",http StatusCode:" + response.getStatusLine().getStatusCode();
                logger.error(content);
            } else {
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "gbk"));
                String lineStr;
                while ((lineStr = reader.readLine()) != null) {
                    sb.append(lineStr);
                }
                reader.close();
            }
        } catch (Exception e) {
            logger.error("======error",e);
        } finally {
            httpget.releaseConnection();
        }
        logger.info("result from http get:" + sb.toString());
        return sb.toString();
    }

    public static void downloadFile(String imaurl,String targetFile) {
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;

        try {
            logger.debug(">>>>>> downloadFile start and imaurl="+imaurl);
            URL url = new URL(imaurl);
            File file = new File(targetFile);
            if(file.exists()){
                file.delete();
                file = new File(targetFile);
//                return;
            }

//            try {
//                Thread.sleep(500);
//            }catch (Exception e){
//                logger.error("thread.sleep interupt",e);
//            }

            checkDirectory(targetFile);

            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream(targetFile);

            byte[] buffer = new byte[1204];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
            logger.debug(">>>>>> downloadFile OK and targetFile="+targetFile);
        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException",e);
        } catch (IOException e) {
            logger.error("IOException",e);
        }
    }

    // 检查路径的所有目录是否创建
    public static void checkDirectory(String path){

        if(Strings.isNullOrEmpty(path)) return;
        if(path.indexOf("img")<=0) return;
        int uploadsIndex = path.indexOf("img");

        String headpath = path.substring(0,uploadsIndex);
        String leftpath = path.substring(uploadsIndex);
        String[] arr = leftpath.split("/");

        String targetpath = headpath;
        for( int i=0;i< arr.length-1;i++){
            targetpath = targetpath +arr[i]+"/";
            createDir(targetpath);
        }
    }

    // 创建目录
    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {// 判断目录是否存在
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {// 结尾是否以"/"结束
            destDirName = destDirName + File.separator;
        }
        if (dir.mkdirs()) {// 创建目标目录
            return true;
        } else {
            return false;
        }
    }

    public static void main(String args[])throws IOException {

        //向文件中写数据

//        FileChannel fc = new FileOutputStream("/Users/chenxuebin/imgs/test.txt").getChannel();
//
//        fc.write(ByteBuffer.wrap("你好，".getBytes()));
//
//        fc.close();

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("memberId", "100000187677"));
//        params.add(new BasicNameValuePair("startTime", ""));
//        params.add(new BasicNameValuePair("endTime", ""));
//        params.add(new BasicNameValuePair("topage", "1"));
//        params.add(new BasicNameValuePair("actionType", "0"));
//        params.add(new BasicNameValuePair("page", "1"));
//        params.add(new BasicNameValuePair("pageSize", "10"));

//        String url = "http://nfyx.jlbry.com/precision/pc/secret/member/index";
        String url = "http://nfyx.jlbry.com/precision/pc/secret/member/detail?memberId=100000187677";
//        httpPostWithCookie(url,params);
        httpGetWithCookie(url,params);


    }

}
